package command;

import util.CommandsStorage;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class CommandParser {
    private static final String EMPTY_CMD = "";

    public static Command parser(String cmdStr) {
        if (cmdStr == null || cmdStr.trim().equals(EMPTY_CMD))
            return new EmptyCommand();

        String[] cmdParams = cmdStr.trim().split(" ");
        String cmd = CommandsStorage.get(cmdParams[0]);

        if (cmd == null)
            return new ErrorCommand();

        if (cmdParams.length == 1)
            return createCommand(cmd, null);
        else
            return createCommand(cmd, Arrays.copyOfRange(cmdParams, 1, cmdParams.length));
    }

    public static Command createCommand(String cmdClassStr, String[] cmdArgs) {
        Class<?> cmdClass = null;
        try {
            cmdClass = Class.forName(cmdClassStr);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Constructor[] constructors = cmdClass.getConstructors();
        Command command = null;
        try {
            if (constructors.length == 1)
                command = (Command) cmdClass.newInstance();
            else {
                for (Constructor constructor : constructors) {
                    if (constructor.getParameterTypes().length > 0 && constructor.getParameterTypes()[0] == String.class) {
                        command = (Command) constructor.newInstance(cmdArgs);
                    }
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return command;
    }

}
